package cn.may.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;

/**
 * @author May
 * @date 2021/03/24 11:58
 */
@Controller
public class FileUploadController {
    /**
     * 配置的上传路径
     */
    @Value("${resource.path}")
    private String resourcePath;
    private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);

    /**
     * 上传文件的页面
     * @return
     */
    @RequestMapping(value = "/uploadPage")
    public String uploadPage() {
        return "uploadPage";
    }

    /**
     * 处理文件上传
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Calendar cal = Calendar.getInstance();
        Integer year = cal.get(Calendar.YEAR);
        Integer month = cal.get(Calendar.MONTH) + 1;
        Integer day = cal.get(Calendar.DAY_OF_MONTH);
        String msg = "SUCCESS";
        String fileName = file.getOriginalFilename();
        //该路径可以从文件中读取，此处演示略
        String filePath =
                resourcePath + File.separator + year + File.separator + month + File.separator + day + File.separator;
        System.out.println("上传路径:" + filePath);
        try {
            uploadFile(file, filePath, fileName);
        } catch (Exception e) {
            msg = e.getMessage();
        }
        //返回json
        return msg;
    }

    /**
     * @Description : 上传文件
     * @param file : 文件实体
     * @param filePath : 文件目标路径
     * @param fileName : 文件名
     * @throws Exception
     */
    public void uploadFile(MultipartFile file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath + fileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        file.transferTo(targetFile);
    }

    @RequestMapping(value = "/uploadStatus")
    @ResponseBody
    public Integer uploadStatus(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object percent = session.getAttribute("upload_percent");
        return null != percent ? (Integer) percent : 0;
    }
}
